﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace Feicui.BeautyCRM.Common
{
    public class AspFormsAuthentication
    {
        /// <summary>
        /// 设置用户登录的凭据（cookie存储）
        /// </summary>
        /// <param name="username"></param>
        /// <param name="isPersistent"></param>
        /// <param name="userData"></param>
        public static void SetFormsAuthentication(string username, bool isPersistent, string userData)
        {
            userData = string.IsNullOrEmpty(userData) ? string.Empty : userData;

            //创建票证
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                username,
                DateTime.Now,
                DateTime.Now.AddMinutes(60),
                isPersistent,
                userData,
                FormsAuthentication.FormsCookiePath);

            // 加密票证
            string encTicket = FormsAuthentication.Encrypt(ticket);

            // 创建cookie
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
            {
                HttpOnly = true,
                Path = FormsAuthentication.FormsCookiePath,
                Secure = false
            };
            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 判断用户是否登陆
        /// </summary>
        /// <returns>True,Fales</returns>
        public static bool isLogin()
        {
            return HttpContext.Current.User.Identity.IsAuthenticated;
        }

        /// <summary>
        /// 注销登陆
        /// </summary>
        public static void logOut()
        {
            FormsAuthentication.SignOut();
        }
        /// <summary>
        /// 获取凭据中的用户名
        /// </summary>
        /// <returns>用户名</returns>
        public static string getUserName()
        {
            if (isLogin())
            {
                return HttpContext.Current.User.Identity.Name;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 获取凭据中的数据
        /// </summary>
        /// <returns>用户信息</returns>
        public static string getUserInfo()
        {
            if (isLogin())
            {
                return ((FormsIdentity)(HttpContext.Current.User.Identity)).Ticket.UserData;
            }
            else
            {
                return null;
            }
        }
    }
}
